const express = require('express');
const router = express.Router();
const crypto = require('crypto');
const jwt = require('jsonwebtoken'); 
const authenticator = require('../middleware/authenticator');
const axios = require('axios');

// 生成一个随机盐
const salt = crypto.randomBytes(16).toString('hex');

const secretKey = 'pp7_secret_key'; 

const generateToken = (userId, username) => {
    const payload = {
        userId,
        username
    };
    const token = jwt.sign(payload, secretKey, { expiresIn: '1h' });
    return token;
};

function userRouteModule(db) {
    // 用户登录
    router.post("/login", async (req, res) => {
        console.log(req.body);
        const { code } = req.body;
        const appId = 'wxb1290600736cde59'; // 替换为你的小程序 AppID
        const appSecret = 'dceee70940b6b5c99645fd5b8848f5ef'; // 替换为你的小程序 AppSecret

        try {
            const wechatResponse = await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
                params: {
                    appid: appId,
                    secret: appSecret,
                    js_code: code,
                    grant_type: 'authorization_code',
                },
            });

            const { openid, session_key } = wechatResponse.data;

            // 先查询数据库中是否已经存在该 openid 对应的用户记录
            const [existingUser] = await db.query('SELECT id FROM users WHERE openid =?', [openid]);
            let userId;
            if (existingUser.length > 0) {
                // 用户已存在，获取用户ID
                userId = existingUser[0].id;
            } else {
                // 用户不存在，插入新用户记录
                // 生成随机密码（这里只是示例，实际可能需要更合理的处理）
                const randomPassword = crypto.randomBytes(8).toString('hex');
                const hashedPassword = crypto.createHmac('sha256', salt).update(randomPassword).digest('hex');

                const [result] = await db.execute(
                    'INSERT INTO users (username, password, salt, openid, role, create_time) VALUES (?,?,?,?,?, NOW())',
                    [openid, hashedPassword, salt, openid, '普通用户'] // 使用 openid 作为用户名（可根据需求修改）
                );
                userId = result[0].insertId;
            }

            // 插入微信登录会话记录
            const expireTime = new Date();
            expireTime.setHours(expireTime.getHours() + 1); // 设置会话一小时后过期，可按需调整
            await db.execute(
                'INSERT INTO wechat_login_sessions (user_id, openid, session_key, login_time, expire_time) VALUES (?,?,?,?,?)',
                [userId, openid, session_key, new Date(), expireTime]
            );

            // 生成 JWT 并返回
            const token = generateToken(userId, openid);
            res.json({ code: 200, message: 'ok', data: { openid, session_key, token } });
        } catch (error) {
            console.error('登录失败:', error);
            if (error.response) {
                res.status(500).json({ success: false, message: error.response.data.errmsg });
            } else {
                res.status(500).json({ success: false, message: '登录失败，服务器错误' });
            }
        }
    });

    return router;
}

module.exports = userRouteModule;